import { reactive } from "vue";
import { useMessage } from 'naive-ui'

interface Msg {
    id?: any;
    msg?: string,
    title: string;
    img?: string;
    type: "default" | "success" | "error" | "warning" | "info" | undefined;
}

export function useLink(callback:Function) {
    const message = useMessage()
    const list = reactive<Msg[]>([]);
    // const socket = new WebSocket("ws://120.48.63.39/ws")
    let socket: WebSocket = null as any;

    const connect = (address: string) => {
        if (socket) {
            socket.close();
            socket = null as any;
        }
        socket = new WebSocket(address);

        socket.onerror = (e: any) => {
            pushData({ msg: "连接失败", title: "错误", type: "error" });
            console.log(e);
        }

        socket.onmessage = (e: any) => {
            // pushData(e.data);
            pushData({ msg: e.data, title: "消息", type: "default" });
            console.log(e);
        }

        socket.onclose = (e: any) => {
            pushData({ msg: "连接已经关闭", title: "提示", type: "warning" });
            console.log(e);
        }

        socket.onopen = (e: any) => {
            pushData({ msg: "连接成功", title: "提示", type: "success" });
            console.log(e);
        }

    }

    const send = (txt: string) => {
        if (!socket) {
            // pushData({ msg: "请先连接服务器", title: "提示", type: "warning" });
            message.warning("请先连接服务器");
            return false;
        }
        if (socket.readyState !== 1) {
            pushData({ msg: "您已经断开连接", title: "提示", type: "warning" });
            return false;
        }
        socket.send(txt);
        return true;
    }

    const close = () => {
        if (!socket) {
            pushData({ msg: "请先连接服务器", title: "提示", type: "warning" });
            return;
        }
        socket.close();
    }

    const clear = () => {
        list.splice(0)
    }

    const addItem = (id: any, str: string, isImage = false) => {
        if (isImage) {
            pushData({ id, img: str, title: "消息", type: "default" });
        }
        else {
            pushData({ id, msg: str, title: "消息", type: "default" });
        }
    }

    const pushData = (item:any)=>{
        list.push(item);
        callback();
    }

    return { list, send, close, clear, connect, addItem };
}